﻿ 
using Azure.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Net.Http.Headers;
using StackExchange.Redis;



//using Newtonsoft.Json;
using System;
using System.IO;
using System.IO.Pipes;
using System.Net.Mime;
using System.Text.Json;
using WebApplication1.Interfaces;
using WebApplication1.Models;
using WebApplication1.Services;
using static System.Net.WebRequestMethods;

namespace FileDownloadAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class FilesController : ControllerBase
    {
        private readonly IFileService _fileService;

        private readonly ILegacyService _legacyService;

        private readonly FileExtensionContentTypeProvider _contentTypeProvider;
        private readonly ILogger<FilesController> _logger;


        public FilesController(IFileService fileService, ILegacyService legacyService, ILogger<FilesController> logger)
        {
            _fileService = fileService;
            _legacyService = legacyService;
            _contentTypeProvider = new FileExtensionContentTypeProvider();

            _logger = logger;

        }

         


      
      
        // POST api/<IndexController>
              [HttpPost]
        //public void Post([FromBody] LoginModel login)
        public async Task<ActionResult> Post2()
        {
            var rawJson = await Request.GetRawBodyAsync();
            string DS_tpabma22 = await _legacyService.CallService_json("qmcc801_web_inq", rawJson);
            return Ok(DS_tpabma22); 
        }


        /// <summary>
        /// 学习示例；
        /// </summary>
        /// <returns></returns>
        private async Task UpdateDownloadCountAsync()
        {
            // 异步执行数据库操作或其他耗时任务
            await Task.Run(() =>
            {
                // 更新下载计数的业务逻辑
                // 例如：数据库操作、文件操作等
                Thread.Sleep(100); // 模拟耗时操作
            });
        }

        private async Task  updateDownloadCount(double item_seq,string certi_no)
        {

            
           var result = new Dictionary<string, object>();

            // 表1数据
            var table1 = new List<Dictionary<string, object>>
            {
                //记录1
                new Dictionary<string, object>
                {
                    ["ITEM_SEQ"] = item_seq,
                    ["CERTI_NO"] = certi_no
                }
                //记录2 
                //,new Dictionary<string, object>
                //{
                //    ["ITEM_SEQ"] = 1,
                //    ["CERTI_NO"] = "张三"
                //}
            };

            // 表2数据,参照如上方法组织；


            result["UPD"] = table1;


            var rawJson = JsonSerializer.Serialize(result);

            //var rawJson = await Request.GetRawBodyAsync();
             await _legacyService.CallService_json("qmcca09_save", rawJson);

            

        }


        [HttpPost("download/get_num")]
        public async Task<IActionResult> DownloadGetNum()
        {
            var rawJson = await Request.GetRawBodyAsync();
            string datset1 = await _legacyService.CallService_json("qmcca09_save", rawJson);
            return Ok(datset1);
        }


        // GET 方式下载（兼容微信）
        [HttpGet("download/single")]
        public async Task<IActionResult> DownloadFileGet(
            [FromQuery] string POUND_NO,
            [FromQuery] string GUID,
            [FromQuery] string CERTI_NO)
        {
            return await DownloadFileInternal(POUND_NO, GUID, CERTI_NO);
        }



        [HttpPost("download/single")]
        public async Task<IActionResult> DownloadSingleFile([FromBody] dynamic request)
        {
            /*
             * 前端传入
            const simpleData = {
                POUND_NO: POUND_NO,
                GUID: GUID
            };
            body: JSON.stringify(simpleData)


            后端接收：
            ValueKind = Object : "{"POUND_NO":"CW25A00668","GUID":"48d7f30f-7813-4e89-8370-3935f5aaabd020251024141507728"}"

            */

            string pound_no = request.GetProperty("POUND_NO").GetString();
            string guid     = request.GetProperty("GUID").GetString();
            string certi_no = request.GetProperty("CERTI_NO").GetString();



            if (guid == null)
                return BadRequest("请选择单个文件");


            return await DownloadFileInternal(pound_no, guid, certi_no);


            //判断文件是否存在，若文件存在，则下载次数+1；
            // var result = await _fileService.DownloadSingleFileAsync(request.FileIds[0]);



            //string filePath = "";
            ////合同号【新能装备的是合同号】 
            //if (pound_no.Length == 10 && pound_no.Substring(0, 2) == "CW")
            //{   //合同号分解；
            //    filePath = Path.Combine(Directory.GetCurrentDirectory(), "Pdf_Files", "_files_xn", pound_no.Substring(2, 2), pound_no.Substring(4, 1), guid+".pdf");
            //}
            //else
            //{
            //    //string str = ClassMyFile.pdf_files(pound_no, guid);
            //}
            /*
            var filePath = await _fileService.GetDownPath(pound_no);
            filePath = Path.Combine(filePath, guid + ".pdf");


            if (!System.IO.File.Exists(filePath))
            {
                return BadRequest("文件不存在");
            }

            //[防止还没更新成功，前台就调用了]
            await updateDownloadCount(18861306, certi_no);

             


             //通过异步方式读取指定路径文件的二进制数据，
             //使用 await 关键字确保文件读取操作完成后再执行后续代码，避免阻塞线程。
             var fileBytes = await System.IO.File.ReadAllBytesAsync(filePath);

             //将读取的二进制数据作为HTTP响应返回给客户端
             return File(fileBytes, "application/pdf", guid + ".pdf");

            */



        }



        /// <summary>
        /// 文件下载接口 - 支持GET和POST-------------------------
        /// </summary>
        [HttpGet("download")]
        [HttpPost("download")]
        public async Task<IActionResult> DownloadFile(
            [FromQuery] string pound_no,
            [FromQuery] string guid,
            [FromQuery] string certi_no,
            [FromBody] dynamic request = null)
        {

            double item_seq = 18861306;

            return await DownloadFileInternal(pound_no, guid, certi_no, item_seq);


            //try
            //{
            //    // 处理POST请求的body参数
            //    //if (request != null)
            //    //{
            //    //    pound_no = request.GetProperty("POUND_NO").GetString();
            //    //    guid = request.GetProperty("GUID").GetString();
            //    //    certi_no = request.GetProperty("CERTI_NO").GetString();

            //    //}

            //    if (guid == null)
            //        return BadRequest("请选择单个文件");

                 

            //    var filePath = await _fileService.GetDownPath(pound_no);
            //    var FileName = guid + ".pdf";
            //    filePath = Path.Combine(filePath, FileName);

            //    if (!System.IO.File.Exists(filePath))
            //    {
            //        return BadRequest("文件不存在"); 
            //    }

             

                
            //    // 读取文件
            //    //var fileStream = System.IO.File.OpenRead(filePath);

            //    //// 设置响应头（重要：支持中文文件名）
            //    //var contentType = "application/octet-stream";
            //    //var encodedFileName = Uri.EscapeDataString(FileName);

            //    //Response.Headers.Add("Content-Disposition",
            //    //    $"attachment; filename=\"{FileName}\"; filename*=utf-8''{encodedFileName}");

            //    //// 返回文件流（注意：不要使用 using，FileResult 会负责释放）
            //    //return File(fileStream, contentType, FileName);

                  

               

            //    // 获取文件流
            //    var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

            //    // 获取Content-Type
            //    if (!_contentTypeProvider.TryGetContentType(FileName, out var contentType))
            //    {
            //        contentType = "application/octet-stream";
            //    }

            //    // 记录下载日志
            //    // await _fileService.RecordDownloadLogAsync(fileId, GetClientInfo());

            //    //[防止还没更新成功，前台就调用了]
            //    await updateDownloadCount(18861306, certi_no);



            //    // 返回文件流
            //    return File(fileStream, contentType, FileName, enableRangeProcessing: true);
                 
            //}
            //catch (Exception ex)
            //{
                
            //    return StatusCode(500, new { success = false, message = "文件下载失败", error = ex.Message });
            //}
        }



        /// <summary>
        /// 文件下载接口 - 支持GET和POST-------------------------
        /// </summary>
        [HttpGet("viewload")]
        [HttpPost("viewload")]
        public async Task<IActionResult> ViewloadFile(
            [FromQuery] string pound_no,
            [FromQuery] string guid,
            [FromQuery] string certi_no,
            [FromBody] dynamic request = null)
        {

            double item_seq = 18861306;

            try
            {
                // 参数验证
                if (string.IsNullOrEmpty(pound_no) ||
                    string.IsNullOrEmpty(guid) ||
                    string.IsNullOrEmpty(certi_no))
                {
                    return BadRequest(new { message = "参数(磅单、质保书证书号、文件名称)不能为空" });
                }


                var FilePath = await _fileService.GetViewPath(pound_no);
                var FileName = guid + ".pdf";
               

                //合同号分解；
                string str = FilePath + "/" + FileName;
               
                string url_str = "/Pdf_Files/web/WorkFlowCardViewer.html?file=../" + str;

                return Redirect(url_str);

                //return Ok(new
                //{ 
                //    viewUrl = url_str,
                //    fileName = FileName
                //});



            }
            catch (Exception ex)
            {
                
                return StatusCode(500, new { message = "文件下载失败", error = ex.Message });
            }








        }


        // 统一的下载逻辑
        private async Task<IActionResult> DownloadFileInternal(string pound_no, string guid, string certi_no,double item_seq)
        { 

            try
            {
                // 参数验证
                if (string.IsNullOrEmpty(pound_no) ||
                    string.IsNullOrEmpty(guid) ||
                    string.IsNullOrEmpty(certi_no))
                {
                    return BadRequest(new { message = "参数(磅单、质保书证书号、文件名称)不能为空" });
                }
                 

                var FilePath = await _fileService.GetDownPath(pound_no);
                var FileName = guid + ".pdf";
                FilePath = Path.Combine(FilePath, FileName);

                if (!System.IO.File.Exists(FilePath))
                {
                    return BadRequest("文件不存在");
                }
                 



                // 获取文件流
                var fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);

                // 获取Content-Type
                if (!_contentTypeProvider.TryGetContentType(FileName, out var contentType))
                {
                    contentType = "application/octet-stream";
                }

                 

                var userAgent = Request.Headers[HeaderNames.UserAgent].ToString();
                bool isWeChat = userAgent.Contains("MicroMessenger");
                var isMobile = userAgent.Contains("Mobile") || userAgent.Contains("Android") || userAgent.Contains("iPhone");
 

                // 记录下载日志到数据库或文件
                _logger.LogInformation("{DateTime}/文件下载,FileName:{FileName}, Client:{Client}, Platform:{Platform},ITEM_SEQ:{item_seq}"
                    , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"),FileName
                    ,isWeChat ? "微信" : "浏览器",
                    isMobile ? "移动端" : "PC端"
                     , item_seq);


               

                //[防止还没更新成功，前台就调用了]
                await updateDownloadCount(item_seq, certi_no);

                // 返回文件流
                return File(fileStream, contentType, FileName, enableRangeProcessing: true);
            }
            catch (Exception ex)
            {
                _logger.LogInformation("{DateTime}/文件下载,pound_no:{pound_no}, guid:{guid}, certi_no:{certi_no},item_seq:{item_seq}"
                   , DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
                   , pound_no, guid, certi_no, item_seq);
                return StatusCode(500, new { message = "文件下载失败", error = ex.Message });
            }
        }










        // 统一的下载逻辑暂时不用，微信浏览器不可以用
        private async Task<IActionResult> DownloadFileInternal(string pound_no, string guid, string certi_no)
        {
            try
            {
                // 参数验证
                if (string.IsNullOrEmpty(pound_no) ||
                    string.IsNullOrEmpty(guid) ||
                    string.IsNullOrEmpty(certi_no))
                {
                    return BadRequest(new { message = "参数不能为空" });
                }




                var filePath = await _fileService.GetDownPath(pound_no);
                var FileName = guid + ".pdf";
                filePath = Path.Combine(filePath, FileName);

                if (!System.IO.File.Exists(filePath))
                {
                    return BadRequest("文件不存在");
                    //return NotFound(new { message = "文件不存在" });
                }

                //[防止还没更新成功，前台就调用了]
                await updateDownloadCount(18861306, certi_no);


                //通过异步方式读取指定路径文件的二进制数据，
                //使用 await 关键字确保文件读取操作完成后再执行后续代码，避免阻塞线程。
                //var fileBytes = await System.IO.File.ReadAllBytesAsync(filePath);

                //将读取的二进制数据作为HTTP响应返回给客户端
                //return File(fileBytes, "application/pdf", guid + ".pdf");



                // 读取文件
                var fileStream = System.IO.File.OpenRead(filePath);

                // 设置响应头（重要：支持中文文件名）
                var contentType = "application/octet-stream";
                var encodedFileName = Uri.EscapeDataString(FileName);

                Response.Headers.Add("Content-Disposition",
                    $"attachment; filename=\"{FileName}\"; filename*=utf-8''{encodedFileName}");

                // 返回文件流（注意：不要使用 using，FileResult 会负责释放）
                return File(fileStream, contentType, FileName);
            }
            catch (Exception ex)
            {
               // _logger.LogError(ex, "文件下载失败: {PoundNo}, {Guid}, {CertiNo}", poundNo, guid, certiNo);
                return StatusCode(500, new { message = "文件下载失败", error = ex.Message });
            }
        }


        [HttpPost("download/batch")]
        public async Task<IActionResult> DownloadBatchFiles([FromBody] List<dynamic> requests)
        {
            double item_seq = 18861306;
            var userAgent = Request.Headers[HeaderNames.UserAgent].ToString();
            bool isWeChat = userAgent.Contains("MicroMessenger");
            var isMobile = userAgent.Contains("Mobile") || userAgent.Contains("Android") || userAgent.Contains("iPhone");


            if (requests.Count() == 0)
            {
                return BadRequest("请选择要下载的文件");
            }
            else if (requests.Count() == 1)
            { 
                dynamic request = requests[0];
                string jsonString = request.ToString();

                dynamic fileData = JsonSerializer.Deserialize<dynamic>(jsonString);

                string guid = fileData.GetProperty("GUID").GetString();
                string pound_no = fileData.GetProperty("POUND_NO").GetString();
                string certi_no = fileData.GetProperty("CERTI_NO").GetString();


                return await DownloadFileInternal(pound_no, guid, certi_no, item_seq);

               
            }


            //批量下载
            var result = await _fileService.DownloadBatchFilesAsync(requests);

            if (!result.Success)
                return BadRequest(result.Message);

            //更新下载次数；
            for (int i = 0; i < requests.Count(); i++)
            { 
                dynamic request = requests[i];
                string jsonString = request.ToString();

                dynamic fileData = JsonSerializer.Deserialize<dynamic>(jsonString);

                string certi_no = fileData.GetProperty("CERTI_NO").GetString();


                //[防止还没更新成功，前台就调用了]
                await updateDownloadCount(item_seq, certi_no);

            
            }


            // 如果是多个文件，当前目录下Path.GetTempPath()生成zip文件，并其对应的ZIP返回
            var zipFilePath = Path.Combine(Path.GetTempPath(), result.FileName);
            if (!System.IO.File.Exists(zipFilePath))
                return BadRequest("ZIP文件不存在");


            // 获取文件流
            var fileStream2 = new FileStream(zipFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
         
            // 获取Content-Type
            if (!_contentTypeProvider.TryGetContentType(result.FileName, out var contentType2))
            {
                contentType2 = "application/octet-stream";
            }

            return File(fileStream2, contentType2, result.FileName, enableRangeProcessing: true);

              
            
        }


       


       

    }



}